#!/usr/bin/python

from globals import log,app
from lircserver import LircServer
from commands import CommandQueue
from btserver import BluetoothServer
from time import sleep
import globals


##include "config.h"
##include "util.h"
##include "sockserver.h" // socket server
##include "btserver.h"   // bluetooth server
##include "lircdaemon.h" // lirc daemon

##include "thread.h"
##include "lircde.h"


#/* ============================================================================= */
#/* FUNCTIONS: IMPLEMENTATIONS */
#/* ============================================================================= */

class MainAppServer:
  _exit = False
  _errors = False
  _errmsg = ""
  
  def init(self, daemonize,  lirc_file):
    log("[MainAppServer] Welcome to Phonemote Server 0.1")

    #lircde_init_mutex();

    #lircde_read_ini_file();

    # if (daemonize) {
    #lircde_log("daemonizing\n");
    #if (daemon(0, 1) < 0) {
    #perror("daemon");
    #exit(1);
    #}
    #fclose(stdout);
    #}

    #// Start LIRC Daemon
    #lirc_daemon_start();
    
    
    lircServer = LircServer(self,  lirc_file);
    queue = CommandQueue(self,  lircServer)
    queue.start()
    lircServer.start()

    #// start socket server
    #//sockserver_init(lircde_port, TRUE);

    # start bluetooth server
    btServer = BluetoothServer(self,  app.btserver_port,queue)
    btServer.start() # no threads for the moment.
    #remoteServer = new RemoteServer(this);
    #new Thread(new ThreadStart(remoteServer.startServer)).Start();

    while True:
        if self._exit: 
            break
        
        try:
            sleep(.5)
        except KeyboardInterrupt:
            print "[MainAppServer] ** Got KeyboardInterrupt **"
            break
    
    if app.verbose:
      log("[MainAppServer] Shutting down phonemote server.")
      
    #lircServer.join()
    self.killthread(btServer,  "Bluetooth Server")
    self.killthread(queue,  "Command Queue")
    self.killthread(lircServer,  "LIRC Server")
   
    if self._errors:
      log("[MainAppServer] ** Exit with error: "+self._errmsg)
      
    if app.verbose:
      log("[MainAppServer] Bye bye.")

    #return TRUE;

  def exit(self):
    self._exit = True

  def die(self,  msg):
    print "*** ERROR *** "+msg
    self._errmsg = msg
    self._errors = True
    self.exit()
    
  def killthread(self,  t,  name):
    if app.verbose:
      log("[MainAppServer] Waiting for "+name+" to shutdown...") 
    
    t.setactive(False)
    #t.join()
    
    if app.verbose:
      log("[MainAppServer] ..."+name+" shutdown complete.")

#void lircde_read_ini_file()
#{
	#lircde_port=2222;
	#btserver_port=BT_PORT;

#}

